package com.lyt.robotocr

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.os.Build
import java.util.*

open class BaseActivity : Activity() {
    protected var times = 0
    private val requestPhonePermissions = 0
    private val requestedPermissions = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    private var init: () -> Unit = {}

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        checkPermission(init)
    }

    protected fun checkPermission(init: () -> Unit = {}) {
        this.init = init
        times++
        val permissionsList: MutableList<String> = ArrayList()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (permission in requestedPermissions) {
                if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) permissionsList.add(
                    permission
                )
            }
            if (permissionsList.size != 0) {
                if (times == 1) {
                    requestPermissions(
                        permissionsList.toTypedArray(),
                        requestPhonePermissions
                    )
                } else {
                    AlertDialog.Builder(this)
                        .setCancelable(false)
                        .setTitle("提示")
                        .setMessage("获取不到授权，APP将无法正常使用，请允许APP获取权限！")
                        .setPositiveButton("确定") { _: DialogInterface?, _: Int ->
                            requestPermissions(
                                permissionsList.toTypedArray(),
                                requestPhonePermissions
                            )
                        }.setNegativeButton("取消") { _: DialogInterface?, _: Int -> finish() }.show()
                }
            } else {
                init()
            }
        } else {
            init()
        }
    }
}